package net.easyunion.dataservice.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * http post ems下单
 * @author lipenghui
 *
 * @version 创建时间：2013年11月14日  下午5:47:12
 */
@Controller
public class SendEms {

	String loginUrl = "http://www.11183.com.cn/ec-web/login.action";
	String vCodeUrl = "http://www.11183.com.cn/ec-web/register/rand.action?type=login&d=";
	String myInfoUrl = "http://www.11183.com.cn/ec-web/jsp/informationAssert/infoindex.action";
	String saveOrderUrl = "http://www.11183.com.cn/ec-web/jsp/shipment/saveShipmentAction.action";
	String arrangeOrderUrl = "http://www.11183.com.cn/ec-web/jsp/order/arrangeOrder.action";
	String findShipUrl = "http://www.11183.com.cn/ec-web/jsp/order/findShipMentDetailAuto.action?shipSid=122329";
	DefaultHttpClient httpclient = new DefaultHttpClient();
	String vCodeCookie = "";

	@RequestMapping(value = "emslogin.do")
	public void emslogin(HttpServletRequest request,
			HttpServletResponse response1) throws IOException {
		// 获取校验码
		String activeCode = request.getParameter("activeCode").toString();
		// 登陆
		login(activeCode);
		// checkLogin();
		// 下单1
		int shipSid = saveOrder();
		// 下单2
		arrangeOrder(shipSid);
	}
	/**
	 * 拿到ems登陆的校验码 并生成jpg返回到页面
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	@RequestMapping(value = "getVCode.do")
	private void getVCode(HttpServletRequest request,
			HttpServletResponse response) throws IOException,
			ClientProtocolException {
		vCodeUrl = vCodeUrl + String.valueOf(Math.random());
		HttpGet vCodeGet = new HttpGet(vCodeUrl);
		HttpResponse vCodeRep = httpclient.execute(vCodeGet);
		Header[] vCodeHeaders = vCodeRep.getHeaders("Set-Cookie");
		for (Header header : vCodeHeaders) {
			System.out.println(header.toString());
			String name = header.getName();
			String value = header.getValue();

			if ("Set-Cookie".equalsIgnoreCase(name)) {
				String[] strs = value.split(";");
				for (String str : strs) {
					String[] cookies = str.split("=");

					if (cookies.length >= 2) {
						String cName = cookies[0];
						String cValue = cookies[1];
						if (cName.contains("JSESSIONID")) {
							vCodeCookie = cValue.trim();
							System.out.println(vCodeCookie);
						}
					}
				}
			}

		}
		InputStream is = vCodeRep.getEntity().getContent();
		byte[] bytes = IOUtils.toByteArray(is);
		is.close();
		response.setContentType("image/jpeg");
		response.getOutputStream().write(bytes);
		response.flushBuffer();
	}
	
	public void login(String activeCode) {
		try {
			// 目标地址
			HttpPost httppost = new HttpPost(loginUrl);

			httppost.setHeader("JSESSIONID", vCodeCookie);

			System.out.println("请求: " + httppost.getRequestLine());
			// 构造最简单的字符串数据
			StringEntity reqEntity = new StringEntity(
					"register.loginId=15618521759&register.password=smiles&checkCode="
							+ activeCode,"utf-8");
			// 设置类型
			reqEntity.setContentType("application/x-www-form-urlencoded");
			// 设置请求的数据
			httppost.setEntity(reqEntity);
			// 执行
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			System.out.println("----------------------------------------");
			System.out.println(response.getStatusLine());
			if (entity != null) {
				System.out.println("Response content length: "
						+ entity.getContentLength());

			}
			EntityUtils.consume(entity);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 到登陆成功页面
	 * 
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public void checkLogin() throws ClientProtocolException, IOException {
		HttpGet infoGet = new HttpGet(myInfoUrl);
		HttpResponse infoResponse = httpclient.execute(infoGet);
		HttpEntity infoEntity = infoResponse.getEntity();
		System.out.println("----------------------------------------");
		System.out.println(infoResponse.getStatusLine());
		if (infoEntity != null) {
			System.out.println("Response content length: "
					+ infoEntity.getContentLength());
		}
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				infoEntity.getContent(), "UTF-8"));
		String line = null;
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
		}
		EntityUtils.consume(infoEntity);
	}

	

	public int saveOrder() throws ClientProtocolException, IOException {
		int shipSid = 0;
		HttpPost httppost = new HttpPost(saveOrderUrl);

		System.out.println("请求: " + httppost.getRequestLine());
		// 构造最简单的字符串数据

		StringEntity reqEntity = new StringEntity(getSaveOrderParam(),"utf-8");
		
		// 设置类型
		reqEntity.setContentType("application/x-www-form-urlencoded");
		// 设置请求的数据
		httppost.setEntity(reqEntity);
		// 执行
		HttpResponse response = httpclient.execute(httppost);

		HttpEntity entity = response.getEntity();
		Header[] headers = response.getAllHeaders();
		for (Header h : headers) {
			String name = h.getName();
			String value = h.getValue();
			System.out.println("header : " + h.getName() + ":" + h.getValue());

			if ("Location".equalsIgnoreCase(name)) {
				String[] strs = value.split("\\?");
				for (String str : strs) {
					String[] ship = str.split("=");
					if (ship.length == 2) {
						shipSid = Integer.parseInt(ship[1]);
					}
				}
			}

		}
		System.out.println(shipSid);
		EntityUtils.consume(entity);
		return shipSid;
	}

	public int arrangeOrder(int shipSid) throws ClientProtocolException, IOException {
		HttpPost httppost = new HttpPost(arrangeOrderUrl);

		System.out.println("请求: " + httppost.getRequestLine());
		// 构造最简单的字符串数据

		StringEntity reqEntity = new StringEntity(getArrayOrderParam(shipSid),"utf-8");
		
		// 设置类型
		reqEntity.setContentType("application/x-www-form-urlencoded");
		// 设置请求的数据
		httppost.setEntity(reqEntity);
		// 执行
		HttpResponse response = httpclient.execute(httppost);

		HttpEntity entity = response.getEntity();
		Header[] headers = response.getAllHeaders();
		for (Header h : headers) {
			String name = h.getName();
			String value = h.getValue();
			System.out.println("header : " + h.getName() + ":" + h.getValue());

//			if ("Location".equalsIgnoreCase(name)) {
//				String[] strs = value.split("\\?");
//				for (String str : strs) {
//					String[] ship = str.split("=");
//					if (ship.length == 2) {
//						shipSid = Integer.parseInt(ship[1]);
//					}
//				}
//			}

		}
		System.out.println(shipSid);
		EntityUtils.consume(entity);
		return shipSid;
	}
	
	/**
	 * 获取下单参数1
	 * @return
	 */
	private String getSaveOrderParam() {
		String param = "autoSendList=-1"
				+"&favouriteLanguage=4158449"
				+"&model.isArray=1"
				+"&model.shipment.count="
				+"&model.shipment.dataChannel=1"
				+"&model.shipment.goodsize="
				+"&model.shipment.ifinsure=0"
				+"&model.shipment.infoKind="
				+"&model.shipment.insuremoney="
				+"&model.shipment.receiveCity=31"
				+"&model.shipment.receiveCounty=310104"
				+"&model.shipment.receiveDetailadd=静安寺"+Math.random()
				+"&model.shipment.receiveMobile=1862160579"
				+"&model.shipment.receiveName=张辰"+Math.random()
				+"&model.shipment.receiveProvince=31"
				+"&model.shipment.receiveTel="
				+"&model.shipment.remark="
				+"&model.shipment.sendCity=11"
				+"&model.shipment.sendCounty=110101"
				+"&model.shipment.sendDetailadd=科学大道"+Math.random()
				+"&model.shipment.sendMobile=15618521759"
				+"&model.shipment.sendName=李朋辉"+Math.random()
				+"&model.shipment.sendProvince=11"
				+"&model.shipment.sendTel="
				+"&model.shipment.type="
				+"&model.shipment.userSid=4695746"
				+"&model.shipment.weight="
				+"&shipment.gooddesc="
				+"&shipment.receiveAddressCode="
				+"&shipment.sendAddressCode="
				+"&telNum_fenji=分机"
				+"&telNum_quhao=区号"
				+"&telNum_tel=电话号码";
		return param;
	}
	
	
	/**
	 * 获取下单参数2
	 * @return
	 */
	private String getArrayOrderParam(int shipSid) {
		String param = "carryenddate=2013-11-21 10:59:43"
				+"&carrystartdate=2013-11-20 10:59:39"
				+"&it="+shipSid
				+"&registerSubscribeInfo.mobileotherSendNotice=true"
				+"&registerSubscribeInfo.mobilereceiveSendNotice=true"
				+"&registerSubscribeInfo.mobilesendAllNotice=true"
				+"&registerSubscribeInfo.otherEmail=15618521756@163.com"
				+"&registerSubscribeInfo.otherMobile=15618521753"
				+"&registerSubscribeInfo.otherReceiveNotice=true"
				+"&registerSubscribeInfo.receiveAllNotice=true"
				+"&registerSubscribeInfo.receiveEmail=15618521755@163.com"
				+"&registerSubscribeInfo.receiveMobile=15618521752"
				+"&registerSubscribeInfo.sendAllNotice=true"
				+"&registerSubscribeInfo.sendEmail=15618521754@163.com"
				+"&registerSubscribeInfo.sendMobile=15618521751"
				+"&shipment.sendAddressCode="
				+"&shipment.sendCity=31"
				+"&shipment.sendCounty=110101"
				+"&shipment.sendDetailadd=静安寺"
				+"&shipment.sendMobile=18621660579"
				+"&shipment.sendName=张辰"
				+"&shipment.sendProvince=31"
				+"&shipment.sendTel="
				+"&telNum_fenji=分机"
				+"&telNum_quhao=区号"
				+"&telNum_tel=电话号码";
		return param;
	}
}
